package mysql

import (
	"database/sql"
	"msems/models"
)

// InsertCol 插入学院
func InsertCol(p *models.ParamCollege) (id int64, err error) {
	//防止跳id
	sqlStr := "ALTER TABLE `s_college` AUTO_INCREMENT =1"
	_, err = db.Exec(sqlStr)
	if err != nil {
		return 0, err
	}
	sqlStr = `insert into s_college(college_name,college_desc) values(?,?)`
	_, err = db.Exec(sqlStr, p.Name, p.Desc)
	if err != nil {
		return 0, err
	}
	sqlStr = `select  id from s_college where college_name=?`
	err = db.Get(&id, sqlStr, p.Name)
	return
}

// UpdateCol 修改
func UpdateCol(p *models.ParamCollege) (err error) {
	sqlStr := "update s_college set college_name=?,college_desc=? where id=?"
	_, err = db.Exec(sqlStr, p.Name, p.Desc, p.ID)
	if err != nil {
		err = nil
	}
	return
}

// DeleteCol 删除学院
func DeleteCol(p *models.ParamCollege) (err error) {
	sqlStr := "delete from s_college where id=?"
	_, err = db.Exec(sqlStr, p.ID)
	if err != nil {
		err = nil
	}

	return
}

// GetColAll 查询所有学院
func GetColAll() (college []*models.College, err error) {
	college = make([]*models.College, 0, 10)
	sqlStr := `select 
       id,college_name,college_desc,create_time
		from s_college`
	err = db.Select(&college, sqlStr)
	if err != nil {
		//查不到记录日志并返回空列表
		if err == sql.ErrNoRows {
			err = nil
		}
	}
	return
}

// AdminLevel 根据ID获取用户的权限
func AdminLevel(id int64) (level int, err error) {
	sqlStr := `select level from admin_user where id=?`
	err = db.Get(&level, sqlStr, id)
	if err != nil {
		return 2, err
	}
	return
}

// AdminLog 插入用户日志
func AdminLog(log *models.AdminLog) (err error) {
	sqlStr := "ALTER TABLE `admin_operation` AUTO_INCREMENT =1"
	_, err = db.Exec(sqlStr)
	sqlStr = `insert into admin_operation(admin_id,operation,message) values(?,?,?)`
	_, err = db.Exec(sqlStr, log.AdminID, log.Operation, log.Message)
	if err != nil {
		return err
	}
	return
}
